package com.example;

/**
 * @Author 苏浩
 * @Date 2022/12/4 16:05
 * @Version 1.0
 * 检查请求数量限制
 */
public class ThrottlingMiddleware extends Middleware {
    private int requestPerMinute;
    private int requestCount;
    private long currentTime;

    public ThrottlingMiddleware(int requestPerMinute) {
        this.requestPerMinute = requestPerMinute;
        this.currentTime = System.currentTimeMillis();
    }

    /**
     * Please, not that checkNext() call can be inserted both in the beginning
     * of this method and in the end.
     *
     * This gives much more flexibility than a simple loop over all middleware
     * objects. For instance, an element of a chain can change the order of
     * checks by running its check after all other checks.
     */
    public boolean check(String email, String password) {
        if (System.currentTimeMillis() > currentTime + 60_000) {
            requestCount = 0;
            currentTime = System.currentTimeMillis();
        }
        requestCount++;
        if (requestCount > requestPerMinute) {
            System.out.println("Request limit exceeded!");
            Thread.currentThread().stop();
        }
        return checkNext(email, password);
    }
}
